package com.huiyun.project.im.core.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.huiyun.project.im.common.auth.AppPrincipal;
import com.huiyun.project.im.common.auth.SecurityUtils;
import com.huiyun.project.im.common.auth.UserPrincipal;
import com.huiyun.project.im.consts.ImCacheConst;
import com.huiyun.project.im.consts.ImServerConst;
import com.huiyun.project.im.consts.ImUserConst;
import com.huiyun.project.im.core.mapper.ImUserMapper;
import com.huiyun.project.im.core.service.IImTenantService;
import com.huiyun.project.im.core.service.IImUserService;
import com.huiyun.project.im.entity.ImTenant;
import com.huiyun.project.im.entity.ImUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//import com.huiyun.project.im.consts.ImCacheConst;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author bogon
 * @since 2020-07-17
 */
@Service
public class ImUserServiceImpl extends ServiceImpl<ImUserMapper, ImUser> implements IImUserService {
    @Autowired
    private IImTenantService tenantService;

    @Cacheable(value = ImCacheConst.USER_CACHE, key = "#uid", unless = "#result==null")

    @Override
    public UserPrincipal findPrincipal(String uid) {
        return baseMapper.findPrincipal(uid);
    }

    /**
     * 新增或更新租户员工账号 普通账号类型
     *
     * @param list
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ImUser> saveOrUpdateTenantUser(List<ImUser> list) {
        //获取登录用户信息
        AppPrincipal appPrincipal = SecurityUtils.getAppPrincipal();
        Assert.notNull(appPrincipal);
        Assert.notEmpty(list);
        Date date = new Date();
        List<ImUser> result = new ArrayList<>();
        String appId=appPrincipal.getId();
        if(appId.startsWith(ImServerConst.APP_STORE_PREFIX)){
            appId=appId.substring(ImServerConst.APP_STORE_PREFIX.length(),appId.length());
        }
        for (ImUser user : list) {
            user.setAppId(appId);
            user.setAppGroupId(appPrincipal.getAppGroupId());
            updateByAppGroupIdAndBid(user);
            //根据 im租户id和登录名查询 imUser用户
            ImUser dbUser = getByAppGroupIdAndUsername(user.getAppGroupId(), user.getUsername());
            if (null == dbUser) {
                this.save(user);
                result.add(user);
            } else {
                //更新,此处不修改别名,单个操作的时候才会修改别名
                dbUser.setModifyTime(date);
                dbUser.setModifyBy(user.getImTenantId());
                dbUser.setNick(user.getNick());
                dbUser.setAlias(user.getAlias());
                dbUser.setAvatar(user.getAvatar());
                dbUser.setUserOrgId(user.getUserOrgId());
                this.updateById(dbUser);
                result.add(dbUser);
            }
        }
        return result;
    }


    /**
     * 新增或更新账号(c端用户)
     *
     * @return
     */
    public void saveOrUpdateUser(ImTenant imTenant, ImUser imUser) {
        //查询是否已存在租户,保存或者修改操作
        ImTenant dbTenant = tenantService.getByAppGroupIdAndBid(imTenant.getAppGroupId(), imTenant.getBid());
        if (dbTenant == null) {
            tenantService.save(imTenant);
        } else {
            dbTenant.setTenantCate(imTenant.getTenantCate());
            dbTenant.setTenantType(imTenant.getTenantType());
            imTenant.setLogo(imTenant.getLogo());
            imTenant.setName(imTenant.getName());
            imTenant.setModifyBy(imTenant.getModifyBy());
            imTenant.setModifyTime(imTenant.getModifyTime());
            tenantService.updateById(dbTenant);
        }
        ImUser dbUser = this.getByAppGroupIdAndUsername(imTenant.getAppGroupId(), imUser.getUsername());
        if (dbUser == null) {
            this.save(imUser);
        } else {
            imUser.setType(ImUserConst.TYPE.TYPE_1.getValue());
            dbUser.setUsername(imUser.getUsername());
            dbUser.setPassword(imUser.getPassword());
            dbUser.setSalt(imUser.getSalt());
            dbUser.setNick(imUser.getNick());
            dbUser.setAlias(imUser.getNick());
            dbUser.setAvatar(imUser.getAvatar());
            dbUser.setUserOrgId(ImUserConst.USER_ORG_0);
            dbUser.setModifyTime(imUser.getModifyTime());
            dbUser.setModifyBy(imUser.getModifyBy());
            this.updateById(dbUser);
        }
    }

    /**
     * 子账号授权取消授权 客服
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserCs(Integer grantType, ImUser user) {
        //根据 im租户id和登录名查询 imUser用户
        ImUser dbUser = getByAppGroupIdAndUsername(user.getAppGroupId(), user.getUsername());
        updateByAppGroupIdAndBid(user);
        //如果是授权
        if (1 == grantType) {
            this.saveOrUpdateTenantUser(Lists.newArrayList(user));
        } else if (0 == user.getType()) {
            dbUser.setDelFlag(ImUserConst.DEL_FLAG_1);
            this.saveOrUpdateTenantUser(Lists.newArrayList(dbUser));
        }
    }

    /**
     * 根据appGroupId和bid修改用户,密码和昵称保持一致
     */
    public void updateByAppGroupIdAndBid(ImUser user) {
        ImUser entity = new ImUser()
                .setPassword(user.getPassword())
                .setNick(user.getNick())
                .setSalt(user.getSalt())
                .setAvatar(user.getAvatar());
        this.update(entity, Wrappers.<ImUser>lambdaQuery()
                .eq(ImUser::getAppGroupId, user.getAppGroupId())
                .eq(ImUser::getBid, user.getBid())
        );
    }

    @Override
    public ImUser findByUsername(String userName) {
        return this.getOne(Wrappers.<ImUser>lambdaQuery().eq(ImUser::getUsername, userName).eq(ImUser::getDelFlag, ImServerConst.DEL_FLAG_0));
    }

    /**
     * 判断用户是否重复
     *
     * @param appGroupId
     * @param username
     * @return
     */
    public ImUser getByAppGroupIdAndUsername(String appGroupId, String username) {
        return this.getOne(Wrappers.<ImUser>lambdaQuery().eq(ImUser::getAppGroupId, appGroupId).eq(ImUser::getUsername, username).eq(ImUser::getDelFlag, ImServerConst.DEL_FLAG_0));
    }


    /**
     * 获取指定客服组的客服列表
     *
     * @param imTenantId
     * @param userOrgId
     * @return
     */
    public List<ImUser> getCsList(String imTenantId, String userOrgId) {
        return this.list(Wrappers.<ImUser>lambdaQuery()
                .eq(ImUser::getImTenantId, imTenantId)
                .eq(StringUtils.isNotBlank(userOrgId), ImUser::getUserOrgId, userOrgId)
                .eq(ImUser::getDelFlag, ImServerConst.DEL_FLAG_0)
                .eq(ImUser::getType, ImUserConst.TYPE.TYPE_2.getValue())
        );
    }

    /**
     * 根据业务系统 bid 和租户id 逻辑删除im账户
     *
     * @return
     */
    @Override
    public List<String> deleteTenantUserByBid(List<String> list, String imTenantId) {
        List<String> result = new ArrayList<>();
        Assert.notEmpty(imTenantId);
        if (CollectionUtil.isNotEmpty(list)) {
            for (String bid : list) {
                boolean b = this.update(Wrappers.<ImUser>lambdaUpdate()
                        .eq(ImUser::getImTenantId, imTenantId)
                        .eq(ImUser::getBid, bid)
                        .set(ImUser::getDelFlag, ImUserConst.DEL_FLAG_1)
                );
                result.add(bid);
            }
        }
        return result;
    }


}
